<template>
  <div class="dljjc_box3_x" style="gap: 8px; display: flex; flex-direction: column">
    <m_load :show="false">
      <template v-slot:nocard>
        <template v-if="cfg.guild.glist == true">
          <n-space justify="center">
            <n-button
              :size="cfg.mobile ? 'small' : ''"
              :type="gd.exp == 'like' ? 'warning' : 'default'"
              @click="gd.button('like')"
              >收藏公会</n-button
            >
            <n-button
              :size="cfg.mobile ? 'small' : ''"
              :type="gd.exp == 'all' ? 'warning' : 'default'"
              @click="gd.button('all')"
              >公会列表</n-button
            >
          </n-space>
          <n-hr />
          <template v-if="gd.exp == 'like'">
            <div class="top_div">
              <n-grid y-gap="12" x-gap="12" :cols="gd.cols">
                <template v-for="item in gd.likedata">
                  <n-gi>
                    <div class="top_div-box">
                      <div @click="gd.clickguild(item)" style="display: flex">
                        <img
                          style="width: 40px; margin-right: 10px"
                          :src="$cfg.function.ava(item.avatar ?? 'sunyeo.png')"
                        />
                      </div>
                      <div @click="gd.clickguild(item)">
                        <p class="_p1" style="width: 147px">{{ item.guild_name }}</p>
                        <p class="_p3">回合 ({{ item.round }})</p>
                        <p class="_p3">伤害 ({{ item.mcdmg?.toLocaleString() }})</p>
                      </div>
                      <div class="_hide" style="position: absolute; right: 2px; top: 2px">
                        <n-button
                          size="tiny"
                          type="warning"
                          quaternary
                          @click="gd.un_like_guild(item)"
                          >取消</n-button
                        >
                      </div>
                    </div>
                  </n-gi>
                </template>
              </n-grid>
            </div>
            <br />
            <n-hr />
          </template>

          <template v-if="gd.exp == 'all'">
            <n-pagination
              :page="Number(gd.page)"
              :on-update:page="gd.pagefun"
              :page-count="gd.maxlist"
              :page-slot="gd.pgs"
            />

            <n-hr />
            <div class="top_div">
              <n-grid y-gap="12" x-gap="12" :cols="gd.cols">
                <template v-for="item in gd.list">
                  <n-gi>
                    <div class="top_div-box">
                      <div @click="gd.clickguild(item)" style="display: flex">
                        <img
                          style="width: 40px; margin-right: 10px"
                          :src="$cfg.function.ava(item.avatar ?? 'sunyeo.png')"
                        />
                      </div>
                      <div @click="gd.clickguild(item)">
                        <p class="_p1">{{ item.guild_name }}</p>
                        <p class="_p3">回合 ({{ item.round }})</p>
                        <p class="_p3">伤害 ({{ item.mcdmg?.toLocaleString() }})</p>
                      </div>
                      <div class="_hide" style="position: absolute; right: 2px; top: 2px">
                        <n-button
                          size="tiny"
                          type="warning"
                          quaternary
                          @click="gd.like_guild(item)"
                          >收藏</n-button
                        >
                      </div>
                    </div>
                  </n-gi>
                </template>
              </n-grid>
            </div>
            <n-hr />
            <n-pagination
              :page="Number(gd.page)"
              :on-update:page="gd.pagefun"
              :page-count="gd.maxlist"
              :page-slot="gd.pgs"
            />
            <br />
          </template>
        </template>

        <template v-if="cfg.guild.glist == false">
          <div>
            <n-space justify="space-between" align="center">
              <n-breadcrumb>
                <n-breadcrumb-item @click="gd.bglist">fa公会列表</n-breadcrumb-item>
                <n-breadcrumb-item>{{ gd.guild.guild_name }}</n-breadcrumb-item>
                <n-breadcrumb-item>{{ gd.vuename }}</n-breadcrumb-item>
              </n-breadcrumb>
              <div></div>
            </n-space>
          </div>
          <n-select
            :size="cfg.mobile ? 'small' : ''"
            v-model:value="gd.season"
            :consistent-menu-width="false"
            :options="cfg.season.select ?? []"
            :style="`width: ${cfg.mobile ? 100 : 100}%`"
            placeholder="请选择赛季"
            @update:value="gd.seasonup"
          />
        </template>
        <slot name="nocard"> </slot>
      </template>
    </m_load>
  </div>
</template>

<script>
import { cfg } from "@/cfg/cfg.js";
import m_load from "@/comp/m_load.vue";

export default {
  components: {
    m_load,
  },
  setup() {
    let gd = cfg.guild;
    if (gd.new == 1) {
    } else {
      gd.new = 1;
      gd.colwd = cfg.mobile == true ? 250 : 250;
      gd.pgwd = cfg.mobile == true ? 45 : 45;
      gd.cols = 1;
      gd.pgs = 7;
      //更新百宝袋缓存【获取二维码】
      gd.upd_guild = async (data) => {
        data.loading = true;
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "guild/load_guild",
            type: "upguild",
            id: gd.guild._id,
          },
        });
      };
      //更新公会数据
      gd.upd_guild = async (data) => {
        data.loading = true;
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "guild/load_guild",
            type: "upguild",
            id: gd.guild._id,
            season: gd.season,
            authkey: cfg.user.authkey,
          },
        });
        res = res.data;
        if (res.code == -1) {
          //时间未到
          if (res.ecode == 2) {
            cfg.msg.error(res.msg);
            data.loading = false;
            return;
          }
          //非本赛季
          if (res.ecode == 1) {
            cfg.msg.error(res.msg);
            data.loading = false;
            return;
          }
        } else {
          gd.guild = res.data;
          gd.updfunc();
        }
        data.loading = false;
      };
      //返回公会列表
      gd.bglist = async () => {
        //清除当前公会数据
        gd.glist = true;
        gd._id = null;
        gd.alldaoss = null;
        gd.alldaoth = null;
        gd.alldao = null;
        gd.guild = {};
        gd.gload = true;

        //读取收藏公会
        gd.like = JSON.parse(localStorage.getItem("guild_like"));
        if (gd.like == null) {
          gd.like = [];
        }
        const ld = Object?.values(gd.like);
        //如果存在收藏公会则通过api获取收藏公会信息
        if (ld?.length >= 1) {
          await gd.get_like_guild();
        }
        //获取普通公会列表
        await gd.get_guild_list();
      };
      //获取全部出刀
      gd.getdao = async () => {
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "guild/report",
            gid: gd.guild.gid, //公会gid
            guild_id: gd.guild.guild_id, //公会id
            length: gd.alldaoth, //当前数据的出刀数 检测是否需要更新
            oldss: gd.alldaoss, //当前数据的赛季
            type: "getall", //获取所有出刀
            season: gd.season, //要获取的赛季
          },
        });
        if (res.data.code == -1) {
          if (res.data.msg == "不需要更新") {
            //不需要更新时的处理
            return false;
          } else {
            cfg.msg.error(res.data.msg);
          }
          return false;
        } else {
          //如果出刀数据不是当前数据则刷新公会数据，
          await gd.loadguild(gd._id, "gdata");
        }
        //存储所有出刀数据
        gd.alldao = res.data.data;
        //存储出刀数据赛季
        gd.alldaoss = gd.season;
        //存储出刀数量
        gd.alldaoth = gd.alldao?.length;
      };
      //按钮切换
      gd.button = (type) => {
        gd.exp = type;
        localStorage.setItem("guild_exp", type);
      };
      //公会列表分页
      gd.pagefun = (pg) => {
        gd.page = pg;
        gd.get_guild_list();
      };
      //点击公会
      gd.clickguild = async (gdata) => {
        gd.glist = false;
        gd._id = gdata._id;
        gd.loadguild(gd._id);
      };
      //替换赛季
      gd.seasonup = async (season) => {
        gd.season = season;
        await gd.loadguild(gd.guild._id, true);
      };

      //加载公会数据
      gd.loadguild = async (gid, re) => {
        try {
          if (re == "gdata") {
            //不处理
          } else {
            gd.gload = true;
            cfg.router.push({
              query: {
                ...cfg.route.query,
                id: gid,
                season: gd.season,
              },
            });
          }

          if (gd.guild.gid == null || re == true || re == "gdata") {
            let res = await cfg.axios.get(`${cfg.url}`, {
              params: {
                t: "v2/get",
                t2: "guild/load_guild",
                id: gid,
                season: gd.season,
                authkey: cfg.user.authkey,
              },
            });
            res = res.data.data;
            if (res.gid == null) {
              gd.glist = false;
              gd.guild = {
                _id: gid,
              };
              cfg.msg.error(`本公会未缓存本赛季`);
              return false;
            }
            gd.guild = res;
            gd.glist = false;
            if (re != "gdata") {
              gd.runfunc();
            }
          }
          gd.gload = false;
          return true;
        } catch (error) {
          alert(`发生错误请刷新页面重试 ${error}`);
          return false;
        }
      };

      //公会取消收藏
      gd.un_like_guild = (gdata) => {
        delete gd.like[gdata.gid];
        localStorage.setItem("guild_like", JSON.stringify(gd.like));
        gd.likedata.splice(gd.likedata.indexOf(gdata), 1);
      };

      //公会收藏
      gd.like_guild = (gdata) => {
        if (gd.like[gdata.gid] == null) {
          gd.like[gdata.gid] = gdata.gid;
          gd.likedata.push(gdata);
          //写入到浏览器缓存guild_like
          localStorage.setItem("guild_like", JSON.stringify(gd.like));
          cfg.msg.success(`收藏公会成功`);
        } else {
          cfg.msg.error(`你已经收藏过该公会了`);
        }
      };

      //收藏列表
      gd.get_like_guild = async () => {
        try {
          let res = await cfg.axios.get(`${cfg.url}`, {
            params: {
              t: "v2/get",
              t2: "guild/get_guild_list",
              type: "like",
              like: gd.like,
            },
          });
          res = res.data.data;
          if (res?.likelist?.length >= 1) {
            gd.likedata = res.likelist;
          }
        } catch (error) {
          alert(`发生错误请刷新页面重试 ${error}`);
        }
      };

      //公会列表
      gd.get_guild_list = async () => {
        try {
          let res = await cfg.axios.get(`${cfg.url}`, {
            params: {
              t: "v2/get",
              t2: "guild/get_guild_list",
              page: gd.page,
            },
          });
          res = res.data.data;
          gd.list = res.list;
          gd.maxlist = res.page;
        } catch (error) {
          cfg.alert3({
            message: `${error}请尝试刷新页面`,
            closeOnClickOverlay: true,
          });
        }
      };
    }

    onMounted(async () => {
      //显示加载窗
      if (gd.guild?.gid == null) {
        gd.guild = {};
      }
      //默认按钮类型
      if (gd.exp == null) {
        if (localStorage.getItem("guild_exp") == null) {
          gd.exp = "all";
        } else {
          gd.exp = localStorage.getItem("guild_exp");
        }
      }

      gd.likedata = [];

      if (gd.season == null) {
        await cfg.function.season_list();
        if (cfg.route.query.season != null) {
          gd.season = parseInt(cfg.route.query.season);
        } else {
          gd.season = cfg.season.list?.[0]?.sid ?? null;
        }
        cfg.router.push({
          query: {
            ...cfg.route.query,
            season: gd.season,
          },
        });
      }

      //检查分页是否为空
      if (gd.page == null) {
        gd.page = 1;
      }

      //检查query是否存在公会id
      if (gd._id == null) {
        if (cfg.route.query.id != null) {
          gd._id = cfg.route.query.id;
        } else {
          gd.glist = true;
        }
      }

      //加载收藏公会
      if (gd.glist == true) {
        if (gd.like == null) {
          if (localStorage.getItem("guild_like") == null) {
            gd.like = {};
          } else {
            gd.like = JSON.parse(localStorage.getItem("guild_like"));
            const ld = Object?.values(gd.like);
            if (ld?.length >= 1) {
              await gd.get_like_guild();
            }
          }
        }
      }

      //加载公会列表
      if (gd.glist == true) {
        await gd.get_guild_list();
      } else {
        if (gd.guild?.gid != null) {
          cfg.router.push({
            query: {
              ...cfg.route.query,
              id: gd.guild._id,
              season: gd.season,
            },
          });
          gd.runfunc();
        } else {
          await gd.loadguild(gd._id);
        }
      }

      gd.pgs = parseInt(cfg.sswd / gd.pgwd);
      gd.cols = parseInt(cfg.sswd / gd.colwd);
    });

    watch(
      () => cfg.sswd,
      (newWidth, oldWidth) => {
        gd.pgs = parseInt(cfg.sswd / gd.pgwd);
        gd.cols = parseInt(cfg.sswd / gd.colwd);
      }
    );

    return {
      cfg,
      gd,
    };
  },
};
</script>
